<template>
  <div class="model-performance">
    <a-form :form="form">
      <a-card title="模型选择" :bordered="false" class="model-select-card">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="模型名称" class="form-item">
              <a-select
                placeholder="请选择模型"
                style="width: 320px"
                v-decorator="[
                  'modelUuid',
                  {
                    rules: [{ required: true, message: '请选择模型' }],
                  },
                ]"
                @change="handleChange"
              >
                <a-select-option v-for="item in modelList" :key="item.uuid" :value="item.uuid">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="模型版本" class="form-item">
              <a-select
                placeholder="请选择版本"
                style="width: 320px"
                v-decorator="[
                  'version',
                  {
                    rules: [{ required: true, message: '请选择版本' }],
                  },
                ]"
              >
                <a-select-option v-for="item in versionList" :key="item" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="性能评估设置" :bordered="false" class="model-performance-card">
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="模型类型">
          <a-select
            placeholder="请选择模型类型"
            v-decorator="[
              'classType',
              {
                rules: [{ required: true, message: '请选择模型类型' }],
              },
            ]"
            @change="handleChangeClassType"
          >
            <a-select-option v-for="item in classTypeList" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="真实标签列">
          <a-input
            placeholder="请输入真实标签列"
            v-decorator="[
              'tLabel',
              {
                rules: [{ required: true, message: '请输入真实标签列' }],
              },
            ]"
          />
          <a-tooltip title="表中业务回流真实标签值的列名，用来计算性能指标">
            <a-icon type="question-circle" class="question-icon" />
          </a-tooltip>
        </a-form-item>
        <a-form-item label="标签分类列" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
          <a-input
            placeholder="请输入标签分类列"
            v-decorator="[
              'labelClassify',
              {
                rules: [{ required: true, message: '请输入标签分类列' }],
              },
            ]"
          />
          <a-tooltip title="表中业务回流真实标签值的列名，用来计算性能指标">
            <a-icon type="question-circle" class="question-icon" />
          </a-tooltip>
        </a-form-item>
        <a-form-item
          label="标签分类类型值"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <dynamic-input-list
            v-decorator="[
              'labelClassifyVal',
              {
                rules: [{ required: true, message: '标签分类类型值' }],
              },
            ]"
            placeholder="请输入标签分类类型值"
            :min-items="1"
            :max-items="10"
          />
        </a-form-item>
        <template v-if="classType === '2'">
          <a-form-item label="预测标签列" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
            <a-select
              placeholder="请选择预测标签列"
              v-decorator="[
                'label',
                {
                  rules: [{ required: true, message: '请选择预测标签列' }],
                },
              ]"
            >
              <a-select-option v-for="item in labelList" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="正样本的概率列"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
          >
            <a-select
              placeholder="请选择正样本的概率列"
              v-decorator="[
                'tProbability',
                {
                  rules: [{ required: true, message: '请选择正样本的概率列' }],
                },
              ]"
            >
              <a-select-option v-for="item in labelList" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
            <a-tooltip title="表中表示正样本概率含义的列名，用来计算性能指标">
              <a-icon type="question-circle" class="question-icon" />
            </a-tooltip>
          </a-form-item>
          <a-form-item
            label="正样本的标签值"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
          >
            <a-input
              placeholder="请输入正样本的标签值"
              v-decorator="[
                'tLabelValue',
                {
                  rules: [{ required: true, message: '请输入正样本的标签值' }],
                },
              ]"
            />
          </a-form-item>
        </template>
        <template v-else>
          <a-form-item label="good标签值" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
            <a-input
              placeholder="请输入good标签值"
              v-decorator="[
                'tValue',
                {
                  rules: [{ required: true, message: '请输入good标签值' }],
                },
              ]"
            />
          </a-form-item>
          <a-form-item label="总分字段" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
            <a-select
              placeholder="请选择总分字段"
              v-decorator="[
                'scoreLabel',
                {
                  rules: [{ required: true, message: '请选择总分字段' }],
                },
              ]"
            >
              <a-select-option v-for="item in labelList" :key="item" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </template>
        <a-form-item label="表现期（天）" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
          <a-input-number
            placeholder="请输入表现期（天）"
            style="width: 100%"
            v-decorator="[
              'hidingPeriod',
              {
                rules: [{ required: true, message: '请输入表现期（天）' }],
              },
            ]"
            :min="0"
          />
          <a-tooltip title="设置真实标签回流所需的天数，系统会根据表现期已满的模型结果进行模型性能评估">
            <a-icon type="question-circle" class="question-icon" />
          </a-tooltip>
        </a-form-item>
      </a-card>
      <a-card title="开关控制" :bordered="false">
        <a-form-item
          label="模型性能开关"
          class="form-item"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="{ ...formItemLayout.wrapperCol, offset: 1 }"
        >
          <a-switch
            v-decorator="['status', { valuePropName: 'checked' }]"
            checked-children="开"
            un-checked-children="关"
          />
        </a-form-item>
      </a-card>
    </a-form>
    <a-divider />
    <div style="text-align: center">
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleSubmit">提交</a-button>
      </a-space>
    </div>
  </div>
</template>

<script>
import { getAllModel } from '@/api/monitor'
import { getModelFields, monitorEvaluate, setMonitorEvaluate } from '@/api/manage'
import { DynamicInputList } from '@/components'

export default {
  name: 'ModelPerformance',
  components: {
    DynamicInputList,
  },
  props: {
    modelDetail: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    const modelData = this.modelDetail
    return {
      modelData,
      form: this.$form.createForm(this),
      modelList: [],
      classTypeList: [
        { value: '2', label: '二分类' },
        { value: '3', label: '评分卡' },
      ],
      versionList: [],
      formItemLayout: {
        labelCol: {
          span: 6,
        },
        wrapperCol: {
          span: 8,
        },
      },
      labelList: [],
      monitorData: {},
      classType: '2',
    }
  },
  mounted() {
    this.getModelList()
    this.getInitData()
  },
  methods: {
    async getModelList() {
      try {
        const res = await getAllModel()
        if (res.code === 200) {
          this.modelList = res.data
          this.$nextTick(() => {
            this.form.setFieldsValue({
              modelUuid: this.modelData.uuid,
              version: this.modelData.version,
            })
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    getInitData() {
      // 所有接口请求结束之后执行
      const params = {
        modelUuid: this.modelData.uuid,
        version: this.modelData.version,
      }
      Promise.all([getModelFields(params), monitorEvaluate(params)]).then((res) => {
        if (res[0].code === 200) {
          this.labelList = res[0].data
        }
        if (res[1].code === 200 && res[1].data) {
          this.monitorData = res[1].data
          this.$nextTick(() => {
            this.classType = this.monitorData.classType
            // 构建表单初始值对象
            this.initFormData()
          })
        } else {
          // 清空表单
          this.form.resetFields()
          // 设置初始值
          this.form.setFieldsValue({
            modelUuid: this.modelData.uuid,
            version: this.modelData.version,
            classType: '2',
            labelClassifyVal: [],
          })
        }
      })
    },
    initFormData() {
      const formValues = {
        classType: this.monitorData.classType,
        label: this.monitorData.label,
        tLabel: this.monitorData.tLabel,
        labelClassify: this.monitorData.labelClassify,
        labelClassifyVal: this.monitorData.labelClassifyVal ? this.monitorData.labelClassifyVal.split(',') : [],
        tProbability: this.monitorData.tProbability,
        tLabelValue: this.monitorData.tLabelValue,
        tValue: this.monitorData.tValue || this.monitorData.tLabelValue,
        // 修复 hidingPeriod 初始化问题
        hidingPeriod:
          this.monitorData.hidingPeriod !== null && this.monitorData.hidingPeriod !== undefined
            ? Number(this.monitorData.hidingPeriod)
            : null,
        status: this.monitorData.status === '1',
      }

      // 修复 scoreLabel 初始化问题 - 只有在评分卡模式下才设置
      if (this.monitorData.classType === '3' && this.monitorData.scoreLabel) {
        formValues.scoreLabel = this.monitorData.scoreLabel
      }
      setTimeout(() => {
        this.form.setFieldsValue(formValues)
      }, 0)
    },
    handleChange(val) {
      const _this = this
      this.$confirm({
        title: '警告',
        content: '更改"模型名称"将丢失当前模型性能配置，确认更改吗？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          _this.versionList = [_this.modelList.find((item) => item.uuid === val).version]
          _this.modelData.version = _this.versionList[0]
          _this.modelData.uuid = val
          _this.getInitData()
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    handleChangeClassType(val) {
      this.classType = val
    },
    handleCancel() {
      this.$emit('close')
    },
    handleSubmit() {
      this.form.validateFields((errors, values) => {
        console.log(errors, values)
        if (errors) {
          return
        }
        const { labelClassifyVal, status } = values
        const params = {
          ...values,
          labelClassifyVal: labelClassifyVal.join(','),
          status: status ? '1' : '0',
          label: values.classType === '2' ? values.label : values.scoreLabel,
          tValue: values.tValue || values.tLabelValue,
        }
        setMonitorEvaluate(params).then((res) => {
          if (res.code === 200) {
            this.$message.success('提交成功')
            this.handleCancel()
            this.$emit('refresh')
          }
        })
      })
    },
  },
}
</script>

<style lang="less" scoped>
.model-performance {
  .question-icon {
    color: @primary-color;
    position: absolute;
    top: 0;
    right: -24px;
  }
}
</style>
